<html lang="en-US">

<head>
    
<title>在 Go 中恰到好处的内存对齐 - 花落雨忧</title>

<meta property="og:title" content="在 Go 中恰到好处的内存对齐 - 花落雨忧">



    



    
    <meta property="description" content="
[&amp;hellip;] type Part1 struct { a bool b int32 c int8 d int64 e byte } 在开始之前，希望你计算一下 Part1 共占用的大小是多少呢？
[&amp;hellip;] func main() { fmt.Printf(&amp;#34;bool size: %d\n&amp;#34;, unsafe.Sizeof(bool(true))) &amp;hellip;">
    <meta property="og:description" content="
[&amp;hellip;] type Part1 struct { a bool b int32 c int8 d int64 e byte } 在开始之前，希望你计算一下 Part1 共占用的大小是多少呢？
[&amp;hellip;] func main() { fmt.Printf(&amp;#34;bool size: %d\n&amp;#34;, unsafe.Sizeof(bool(true))) &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/talk/2018-12-26-go-memory-align/">在 Go 中恰到好处的内存对齐</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/12/26</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p><img src="https://s2.ax1x.com/2020/02/27/3wuT0A.png" alt="image"></p>
<h2 id="问题">问题</h2>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Part1</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">a</span> <span style="color:#66d9ef">bool</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span> <span style="color:#66d9ef">int32</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span> <span style="color:#66d9ef">int8</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">d</span> <span style="color:#66d9ef">int64</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">byte</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在开始之前，希望你计算一下 <code>Part1</code> 共占用的大小是多少呢？</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;bool size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(bool(<span style="color:#66d9ef">true</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int32 size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(int32(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int8 size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(int8(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int64 size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(int64(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;byte size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(byte(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;string size: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(<span style="color:#e6db74">&#34;EDDYCJY&#34;</span>))
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>输出结果：</p>
<pre tabindex="0"><code>bool size: 1
int32 size: 4
int8 size: 1
int64 size: 8
byte size: 1
string size: 16
</code></pre><p>这么一算，<code>Part1</code> 这一个结构体的占用内存大小为 1+4+1+8+1 = 15 个字节。相信有的小伙伴是这么算的，看上去也没什么毛病</p>
<p>真实情况是怎么样的呢？我们实际调用看看，如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Part1</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">a</span> <span style="color:#66d9ef">bool</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span> <span style="color:#66d9ef">int32</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span> <span style="color:#66d9ef">int8</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">d</span> <span style="color:#66d9ef">int64</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">byte</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">part1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">Part1</span>{}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;part1 size: %d, align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(<span style="color:#a6e22e">part1</span>), <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(<span style="color:#a6e22e">part1</span>))
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>输出结果：</p>
<pre tabindex="0"><code>part1 size: 32, align: 8
</code></pre><p>最终输出为占用 32 个字节。这与前面所预期的结果完全不一样。这充分地说明了先前的计算方式是错误的。为什么呢？</p>
<p>在这里要提到 “内存对齐” 这一概念，才能够用正确的姿势去计算，接下来我们详细的讲讲它是什么</p>
<h2 id="内存对齐">内存对齐</h2>
<p>有的小伙伴可能会认为内存读取，就是一个简单的字节数组摆放</p>
<p><img src="https://s2.ax1x.com/2020/02/27/3wuLff.png" alt="image"></p>
<p>上图表示一个坑一个萝卜的内存读取方式。但实际上 CPU 并不会以一个一个字节去读取和写入内存。相反 CPU 读取内存是<strong>一块一块读取</strong>的，块的大小可以为 2、4、6、8、16 字节等大小。块大小我们称其为<strong>内存访问粒度</strong>。如下图：</p>
<p><img src="https://s2.ax1x.com/2020/02/27/3wKSmj.png" alt="image"></p>
<p>在样例中，假设访问粒度为 4。 CPU 是以每 4 个字节大小的访问粒度去读取和写入内存的。这才是正确的姿势</p>
<h3 id="为什么要关心对齐">为什么要关心对齐</h3>
<ul>
<li>你正在编写的代码在性能（CPU、Memory）方面有一定的要求</li>
<li>你正在处理向量方面的指令</li>
<li>某些硬件平台（ARM）体系不支持未对齐的内存访问</li>
</ul>
<p>另外作为一个工程师，你也很有必要学习这块知识点哦 :)</p>
<h3 id="为什么要做对齐">为什么要做对齐</h3>
<ul>
<li>平台（移植性）原因：不是所有的硬件平台都能够访问任意地址上的任意数据。例如：特定的硬件平台只允许在特定地址获取特定类型的数据，否则会导致异常情况</li>
<li>性能原因：若访问未对齐的内存，将会导致 CPU 进行两次内存访问，并且要花费额外的时钟周期来处理对齐及运算。而本身就对齐的内存仅需要一次访问就可以完成读取动作</li>
</ul>
<p><img src="https://s2.ax1x.com/2020/02/27/3wKApT.png" alt="image"></p>
<p>在上图中，假设从 Index 1 开始读取，将会出现很崩溃的问题。因为它的内存访问边界是不对齐的。因此 CPU 会做一些额外的处理工作。如下：</p>
<ol>
<li>CPU <strong>首次</strong>读取未对齐地址的第一个内存块，读取 0-3 字节。并移除不需要的字节 0</li>
<li>CPU <strong>再次</strong>读取未对齐地址的第二个内存块，读取 4-7 字节。并移除不需要的字节 5、6、7 字节</li>
<li>合并 1-4 字节的数据</li>
<li>合并后放入寄存器</li>
</ol>
<p>从上述流程可得出，不做 “内存对齐” 是一件有点 &ldquo;麻烦&rdquo; 的事。因为它会增加许多耗费时间的动作</p>
<p>而假设做了内存对齐，从 Index 0 开始读取 4 个字节，只需要读取一次，也不需要额外的运算。这显然高效很多，是标准的<strong>空间换时间</strong>做法</p>
<h3 id="默认系数">默认系数</h3>
<p>在不同平台上的编译器都有自己默认的 “对齐系数”，可通过预编译命令 <code>#pragma pack(n)</code> 进行变更，n 就是代指 “对齐系数”。一般来讲，我们常用的平台的系数如下：</p>
<ul>
<li>32 位：4</li>
<li>64 位：8</li>
</ul>
<p>另外要注意，不同硬件平台占用的大小和对齐值都可能是不一样的。因此本文的值不是唯一的，调试的时候需按本机的实际情况考虑</p>
<h3 id="成员对齐">成员对齐</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;bool align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(bool(<span style="color:#66d9ef">true</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int32 align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(int32(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int8 align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(int8(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;int64 align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(int64(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;byte align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(byte(<span style="color:#ae81ff">0</span>)))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;string align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(<span style="color:#e6db74">&#34;EDDYCJY&#34;</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;map align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">string</span>]<span style="color:#66d9ef">string</span>{}))
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>输出结果：</p>
<pre tabindex="0"><code>bool align: 1
int32 align: 4
int8 align: 1
int64 align: 8
byte align: 1
string align: 8
map align: 8
</code></pre><p>在 Go 中可以调用 <code>unsafe.Alignof</code> 来返回相应类型的对齐系数。通过观察输出结果，可得知基本都是 <code>2^n</code>，最大也不会超过 8。这是因为我手提（64 位）编译器默认对齐系数是 8，因此最大值不会超过这个数</p>
<h3 id="整体对齐">整体对齐</h3>
<p>在上小节中，提到了结构体中的成员变量要做字节对齐。那么想当然身为最终结果的结构体，也是需要做字节对齐的</p>
<h3 id="对齐规则">对齐规则</h3>
<ul>
<li>结构体的成员变量，第一个成员变量的偏移量为 0。往后的每个成员变量的对齐值必须为<strong>编译器默认对齐长度</strong>（<code>#pragma pack(n)</code>）或<strong>当前成员变量类型的长度</strong>（<code>unsafe.Sizeof</code>），取<strong>最小值作为当前类型的对齐值</strong>。其偏移量必须为对齐值的整数倍</li>
<li>结构体本身，对齐值必须为<strong>编译器默认对齐长度</strong>（<code>#pragma pack(n)</code>）或<strong>结构体的所有成员变量类型中的最大长度</strong>，取<strong>最大数的最小整数倍</strong>作为对齐值</li>
<li>结合以上两点，可得知若<strong>编译器默认对齐长度</strong>（<code>#pragma pack(n)</code>）超过结构体内成员变量的类型最大长度时，默认对齐长度是没有任何意义的</li>
</ul>
<h2 id="分析流程">分析流程</h2>
<p>接下来我们一起分析一下，“它” 到底经历了些什么，影响了 “预期” 结果</p>
<table>
<thead>
<tr>
<th>成员变量</th>
<th>类型</th>
<th>偏移量</th>
<th>自身占用</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>bool</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>字节对齐</td>
<td>无</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>b</td>
<td>int32</td>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>c</td>
<td>int8</td>
<td>8</td>
<td>1</td>
</tr>
<tr>
<td>字节对齐</td>
<td>无</td>
<td>9</td>
<td>7</td>
</tr>
<tr>
<td>d</td>
<td>int64</td>
<td>16</td>
<td>8</td>
</tr>
<tr>
<td>e</td>
<td>byte</td>
<td>24</td>
<td>1</td>
</tr>
<tr>
<td>字节对齐</td>
<td>无</td>
<td>25</td>
<td>7</td>
</tr>
<tr>
<td>总占用大小</td>
<td>-</td>
<td>-</td>
<td>32</td>
</tr>
</tbody>
</table>
<h3 id="成员对齐-1">成员对齐</h3>
<ul>
<li>第一个成员 a
<ul>
<li>类型为 bool</li>
<li>大小/对齐值为 1 字节</li>
<li>初始地址，偏移量为 0。占用了第 1 位</li>
</ul>
</li>
<li>第二个成员 b
<ul>
<li>类型为 int32</li>
<li>大小/对齐值为 4 字节</li>
<li>根据规则 1，其偏移量必须为 4 的整数倍。确定偏移量为 4，因此 2-4 位为 Padding。而当前数值从第 5 位开始填充，到第 8 位。如下：axxx|bbbb</li>
</ul>
</li>
<li>第三个成员 c
<ul>
<li>类型为 int8</li>
<li>大小/对齐值为 1 字节</li>
<li>根据规则 1，其偏移量必须为 1 的整数倍。当前偏移量为 8。不需要额外对齐，填充 1 个字节到第 9 位。如下：axxx|bbbb|c&hellip;</li>
</ul>
</li>
<li>第四个成员 d
<ul>
<li>类型为 int64</li>
<li>大小/对齐值为 8 字节</li>
<li>根据规则 1，其偏移量必须为 8 的整数倍。确定偏移量为 16，因此 9-16 位为 Padding。而当前数值从第 17 位开始写入，到第 24 位。如下：axxx|bbbb|cxxx|xxxx|dddd|dddd</li>
</ul>
</li>
<li>第五个成员 e
<ul>
<li>类型为 byte</li>
<li>大小/对齐值为 1 字节</li>
<li>根据规则 1，其偏移量必须为 1 的整数倍。当前偏移量为 24。不需要额外对齐，填充 1 个字节到第 25 位。如下：axxx|bbbb|cxxx|xxxx|dddd|dddd|e&hellip;</li>
</ul>
</li>
</ul>
<h3 id="整体对齐-1">整体对齐</h3>
<p>在每个成员变量进行对齐后，根据规则 2，整个结构体本身也要进行字节对齐，因为可发现它可能并不是 <code>2^n</code>，不是偶数倍。显然不符合对齐的规则</p>
<p>根据规则 2，可得出对齐值为 8。现在的偏移量为 25，不是 8 的整倍数。因此确定偏移量为 32。对结构体进行对齐</p>
<h3 id="结果">结果</h3>
<p>Part1 内存布局：axxx|bbbb|cxxx|xxxx|dddd|dddd|exxx|xxxx</p>
<h3 id="小结">小结</h3>
<p>通过本节的分析，可得知先前的 “推算” 为什么错误？</p>
<p>是因为实际内存管理并非 “一个萝卜一个坑” 的思想。而是一块一块。通过空间换时间（效率）的思想来完成这块读取、写入。另外也需要兼顾不同平台的内存操作情况</p>
<h2 id="巧妙的结构体">巧妙的结构体</h2>
<p>在上一小节，可得知根据成员变量的类型不同，其结构体的内存会产生对齐等动作。那假设字段顺序不同，会不会有什么变化呢？我们一起来试试吧 :-)</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Part1</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">a</span> <span style="color:#66d9ef">bool</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span> <span style="color:#66d9ef">int32</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span> <span style="color:#66d9ef">int8</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">d</span> <span style="color:#66d9ef">int64</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">byte</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Part2</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">byte</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span> <span style="color:#66d9ef">int8</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">a</span> <span style="color:#66d9ef">bool</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span> <span style="color:#66d9ef">int32</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">d</span> <span style="color:#66d9ef">int64</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">part1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">Part1</span>{}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">part2</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">Part2</span>{}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;part1 size: %d, align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(<span style="color:#a6e22e">part1</span>), <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(<span style="color:#a6e22e">part1</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;part2 size: %d, align: %d\n&#34;</span>, <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Sizeof</span>(<span style="color:#a6e22e">part2</span>), <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Alignof</span>(<span style="color:#a6e22e">part2</span>))
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>输出结果：</p>
<pre tabindex="0"><code>part1 size: 32, align: 8
part2 size: 16, align: 8
</code></pre><p>通过结果可以惊喜的发现，只是 “简单” 对成员变量的字段顺序进行改变，就改变了结构体占用大小</p>
<p>接下来我们一起剖析一下 <code>Part2</code>，看看它的内部到底和上一位之间有什么区别，才导致了这样的结果？</p>
<h3 id="分析流程-1">分析流程</h3>
<table>
<thead>
<tr>
<th>成员变量</th>
<th>类型</th>
<th>偏移量</th>
<th>自身占用</th>
</tr>
</thead>
<tbody>
<tr>
<td>e</td>
<td>byte</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>c</td>
<td>int8</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>a</td>
<td>bool</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>字节对齐</td>
<td>无</td>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>int32</td>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>d</td>
<td>int64</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>总占用大小</td>
<td>-</td>
<td>-</td>
<td>16</td>
</tr>
</tbody>
</table>
<h4 id="成员对齐-2">成员对齐</h4>
<ul>
<li>第一个成员 e
<ul>
<li>类型为 byte</li>
<li>大小/对齐值为 1 字节</li>
<li>初始地址，偏移量为 0。占用了第 1 位</li>
</ul>
</li>
<li>第二个成员 c
<ul>
<li>类型为 int8</li>
<li>大小/对齐值为 1 字节</li>
<li>根据规则 1，其偏移量必须为 1 的整数倍。当前偏移量为 2。不需要额外对齐</li>
</ul>
</li>
<li>第三个成员 a
<ul>
<li>类型为 bool</li>
<li>大小/对齐值为 1 字节</li>
<li>根据规则 1，其偏移量必须为 1 的整数倍。当前偏移量为 3。不需要额外对齐</li>
</ul>
</li>
<li>第四个成员 b
<ul>
<li>类型为 int32</li>
<li>大小/对齐值为 4 字节</li>
<li>根据规则 1，其偏移量必须为 4 的整数倍。确定偏移量为 4，因此第 3 位为 Padding。而当前数值从第 4 位开始填充，到第 8 位。如下：ecax|bbbb</li>
</ul>
</li>
<li>第五个成员 d
<ul>
<li>类型为 int64</li>
<li>大小/对齐值为 8 字节</li>
<li>根据规则 1，其偏移量必须为 8 的整数倍。当前偏移量为 8。不需要额外对齐，从 9-16 位填充 8 个字节。如下：ecax|bbbb|dddd|dddd</li>
</ul>
</li>
</ul>
<h4 id="整体对齐-2">整体对齐</h4>
<p>符合规则 2，不需要额外对齐</p>
<h4 id="结果-1">结果</h4>
<p>Part2 内存布局：ecax|bbbb|dddd|dddd</p>
<h2 id="总结">总结</h2>
<p>通过对比 <code>Part1</code> 和 <code>Part2</code> 的内存布局，你会发现两者有很大的不同。如下：</p>
<ul>
<li>
<p>Part1：axxx|bbbb|cxxx|xxxx|dddd|dddd|exxx|xxxx</p>
</li>
<li>
<p>Part2：ecax|bbbb|dddd|dddd</p>
</li>
</ul>
<p>仔细一看，<code>Part1</code> 存在许多 Padding。显然它占据了不少空间，那么 Padding 是怎么出现的呢？</p>
<p>通过本文的介绍，可得知是由于不同类型导致需要进行字节对齐，以此保证内存的访问边界</p>
<p>那么也不难理解，为什么<strong>调整结构体内成员变量的字段顺序</strong>就能达到缩小结构体占用大小的疑问了，是因为巧妙地减少了 Padding 的存在。让它们更 “紧凑” 了。这一点对于加深 Go 的内存布局印象和大对象的优化非常有帮</p>
<p>当然了，没什么特殊问题，你可以不关注这一块。但你要知道这块知识点 😄</p>
<h2 id="参考">参考</h2>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Data_structure_alignment">Data structure alignment</a></li>
<li><a href="https://www.ibm.com/developerworks/library/pa-dalign/">Data alignment</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/pkg/2018-12-15-unsafe/">有点不安全却又一亮的 Go unsafe.Pointer</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/slice/2018-12-11-slice/">深入理解 Go Slice</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/pkg/2018-12-04-fmt/">fmt 标准库 --- Print* 是怎么样输出的？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/talk/2018-11-25-gomock/">使用 Gomock 进行单元测试</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-20-zipkin/">「连载十」分布式链路追踪 gRPC &#43; Opentracing &#43; Zipkin</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/pkg/2018-12-15-unsafe/"
                                                    rel="prev">有点不安全却又一亮的 Go unsafe.Pointer</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/slice/2019-01-06-why-slice-max/">Go Slice 最大容量大小是怎么来的</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>